package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.handler.UserInfoRedisHandler;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.RequireLogin;
import cn.wolfcode.luowowo.website.util.UserContext;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Administrator on 2019/7/8.
 */
public class CheckLoginInterceptor implements HandlerInterceptor {

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //最开始,我们判断这是一个静态请求还是动态请求,如果是动态请求,我们才进行下面这些操作,否者直接放行
        if (handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod) handler;
            //判断当前方法是否有@RequiredLogin这个注解,如果有就进行登录拦截
            if (hm.hasMethodAnnotation(RequireLogin.class)) {
                //登录校验
                //1.获取浏览器发送请求中的cookie
                Cookie cookie = UserContext.getCookie(request, UserInfoRedisHandler.TOKEN_COOKIE);
                //2.判断获取出来的cookie是否有值,有值,就获取里面的value,再去redis里面获取对应的value
                UserInfo userInfo = null;
                if (cookie != null) {
                    userInfo = userInfoRedisService.get(UserInfoRedisHandler.USER_INFO_REDIS_HANDLER, cookie.getValue());
                }
                //如果获取出来的userInfo对象为空,就表示该方法需要登录之后才能访问,且这次请求是非登录状态下发送的
                if (userInfo == null) {
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
        return true;
    }
}
